#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/3 1:02
# @Author : 闫峰
# @File    : receiver.py
import json

import pika


class RabbitMQReceiver:
    def __init__(self, host, queue, username, password, callback):
        credentials = pika.PlainCredentials(username, password)
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host, credentials=credentials))
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=queue)
        self.queue = queue
        self.callback = callback

    def start(self):
        # 定义回调函数来处理接收到的消息
        def on_message_callback(ch, method, properties, body):
            # 将接收到消息反序列化为Python对象
            message = json.loads(body)
            self.callback(message)

        # 接收消息
        self.channel.basic_consume(queue=self.queue, on_message_callback=on_message_callback,auto_ack=True)
        self.channel.start_consuming()

    def close(self):
        self.connection.close()